package com.kingwang.demo.springsecuritytokendemo.security;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于Token方式认证的Spring Security AuthenticationToken
 */
@EqualsAndHashCode(callSuper = true)
public class TokenBasedAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = -3102504825038040069L;

    /**
     * 额外属性
     */
    @Getter
    private Map<String, String> attributes = new HashMap<>();

    /**
     * Token类型
     */
    @Getter
    private String tokenType;

    /**
     * Token值
     */
    @Getter
    private String token;

    public TokenBasedAuthenticationToken(String tokenType, String token) {
        super(null);
        this.tokenType = tokenType;
        this.token = token;
        setAuthenticated(false);
    }

    public TokenBasedAuthenticationToken(String tokenType, String token,
                                         Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.tokenType = tokenType;
        this.token = token;
        setAuthenticated(true);
    }

    /**
     * 添加额外属性
     *
     * @param name
     * @param value
     */
    public void setAttribute(String name, String value) {
        this.attributes.put(name, value);
    }

    /**
     * 删除额外属性
     *
     * @param name
     */
    public void removeAttribute(String name) {
        this.attributes.remove(name);
    }

    /**
     * 获取额外属性
     *
     * @param name
     * @return
     */
    public String getAttribute(String name) {
        return this.attributes.get(name);
    }

    @Override
    public Object getCredentials() {
        return this.token;
    }

    @Override
    public Object getPrincipal() {
        return this.tokenType;
    }
}
